<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="第2章：this全面解析2.1 调用位置 在理解this的绑定之前，首先要理解“函数调用的位置”，即函数在代码中被调用的位置。只有仔细分析了调用位置才能解释，函数中的this到底引用的是什么？ 寻找“函数被调用的位置”，其实并没有想象中的简单，因为JS是很灵活的语言，经常将函数也作为参数进行传递，可能会隐藏真正的调用位置。 所以我们需要分析函数的调用栈。所谓调用栈，就是为了到达当前执行位置，所调用">
<meta property="og:type" content="article">
<meta property="og:title" content="《你不知道的JavaScript(上)》S02E02">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E02/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="第2章：this全面解析2.1 调用位置 在理解this的绑定之前，首先要理解“函数调用的位置”，即函数在代码中被调用的位置。只有仔细分析了调用位置才能解释，函数中的this到底引用的是什么？ 寻找“函数被调用的位置”，其实并没有想象中的简单，因为JS是很灵活的语言，经常将函数也作为参数进行传递，可能会隐藏真正的调用位置。 所以我们需要分析函数的调用栈。所谓调用栈，就是为了到达当前执行位置，所调用">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-12-01T14:20:17.000Z">
<meta property="article:modified_time" content="2020-12-01T15:07:11.592Z">
<meta property="article:author" content="William Leung">
<meta property="article:tag" content="你不知道的JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E02/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>《你不知道的JavaScript(上)》S02E02 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC2%E7%AB%A0%EF%BC%9Athis%E5%85%A8%E9%9D%A2%E8%A7%A3%E6%9E%90"><span class="nav-number">1.</span> <span class="nav-text">第2章：this全面解析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E8%B0%83%E7%94%A8%E4%BD%8D%E7%BD%AE"><span class="nav-number">1.1.</span> <span class="nav-text">2.1 调用位置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E7%BB%91%E5%AE%9A%E8%A7%84%E5%88%99"><span class="nav-number">1.2.</span> <span class="nav-text">2.2 绑定规则</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-%E9%BB%98%E8%AE%A4%E7%BB%91%E5%AE%9A"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">2.2.1 默认绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-2-%E9%9A%90%E5%BC%8F%E7%BB%91%E5%AE%9A"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">2.2.2 隐式绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-3-%E6%98%BE%E7%A4%BA%E7%BB%91%E5%AE%9A"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">2.2.3 显示绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-4-new%E7%BB%91%E5%AE%9A"><span class="nav-number">1.2.0.4.</span> <span class="nav-text">2.2.4 new绑定</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-number">1.3.</span> <span class="nav-text">2.3 优先级</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-%E7%BB%91%E5%AE%9A%E4%BE%8B%E5%A4%96"><span class="nav-number">1.4.</span> <span class="nav-text">2.4 绑定例外</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-1-%E8%A2%AB%E5%BF%BD%E7%95%A5%E7%9A%84this"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">2.4.1 被忽略的this</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-2-%E9%97%B4%E6%8E%A5%E5%BC%95%E7%94%A8"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">2.4.2 间接引用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-3-%E8%BD%AF%E7%BB%91%E5%AE%9A"><span class="nav-number">1.4.0.3.</span> <span class="nav-text">2.4.3 软绑定</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-5-this%E8%AF%8D%E6%B3%95"><span class="nav-number">1.5.</span> <span class="nav-text">2.5 this词法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-%E5%B0%8F%E7%BB%93"><span class="nav-number">1.6.</span> <span class="nav-text">2.6 小结</span></a></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《你不知道的JavaScript(上)》S02E02
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2020-12-01 22:20:17 / 修改时间：23:07:11" itemprop="dateCreated datePublished" datetime="2020-12-01T22:20:17+08:00">2020-12-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>8.3k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>8 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第2章：this全面解析"><a href="#第2章：this全面解析" class="headerlink" title="第2章：this全面解析"></a>第2章：this全面解析</h1><h2 id="2-1-调用位置"><a href="#2-1-调用位置" class="headerlink" title="2.1 调用位置"></a>2.1 调用位置</h2><ul>
<li>在理解this的绑定之前，首先要理解“函数调用的位置”，即函数在代码中被调用的位置。只有仔细分析了调用位置才能解释，函数中的this到底引用的是什么？</li>
<li>寻找“函数被调用的位置”，其实并没有想象中的简单，因为JS是很灵活的语言，经常将函数也作为参数进行传递，可能会隐藏真正的调用位置。</li>
<li>所以我们需要分析函数的调用栈。所谓调用栈，就是为了到达当前执行位置，所调用过的所有函数，所以我们可以把调用栈想象成一个函数调用链，举例说明：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">baz</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//当前位置是baz</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;my name is baz&quot;</span>);</span><br><span class="line">    <span class="comment">//baz中调用bar</span></span><br><span class="line">    bar();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//当前位置是bar</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;my name is bar&quot;</span>);</span><br><span class="line">    <span class="comment">//bar中调用foo</span></span><br><span class="line">    foo();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//当前位置是foo</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;my name is foo&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//window下调用baz</span></span><br><span class="line">baz();</span><br><span class="line"></span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment"> * 所以foo的调用栈(链)就是：</span></span><br><span class="line"><span class="comment"> * window -&gt; baz -&gt; bar -&gt; foo</span></span><br><span class="line"><span class="comment"> * /</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="2-2-绑定规则"><a href="#2-2-绑定规则" class="headerlink" title="2.2 绑定规则"></a>2.2 绑定规则</h2><ul>
<li>通过函数的调用位置，并应用JavaScript中四条决定this绑定的规则，就能分析this的引用值了。<h4 id="2-2-1-默认绑定"><a href="#2-2-1-默认绑定" class="headerlink" title="2.2.1 默认绑定"></a>2.2.1 默认绑定</h4></li>
<li>首先是最常用的函数调用类型：独立函数调用。所谓独立函数调用，就是没有应用其他规则的默认调用规则。举例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);   </span><br><span class="line">&#125;</span><br><span class="line">foo();  <span class="comment">//输出 2</span></span><br></pre></td></tr></table></figure></li>
<li>当调用<code>foo()</code>函数时，<code>this.a</code>指向了全局变量<code>a</code>，因为在默认绑定下，<code>this</code>指向全局对象。</li>
<li>那如何辨别这里应用的是默认绑定呢？这时候，就需要运用我们前面讲的“分析函数调用位置”了，在这段代码中，<code>foo()</code>函数是直接调用的，不带任何修饰，也不被任何函数包含，所以可以确定是默认绑定。<blockquote>
<p>注意：如果 <strong>函数内使用严格模式(strict mode)</strong> ，是不能将全局对象用于默认绑定的，最终<code>this</code>会绑定到<code>undefined</code>上。举例说明：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123; </span><br><span class="line"><span class="meta">  &quot;use strict&quot;</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line">foo();    <span class="comment">//输出 TypeError : this is undefined</span></span><br></pre></td></tr></table></figure>
<p>但 <strong>在严格模式下调用函数</strong> ，则不影响默认绑定。举例说明：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 2;</span><br><span class="line">function foo()&#123;</span><br><span class="line">  console.log(this.a);</span><br><span class="line">&#125;</span><br><span class="line">(function()&#123;</span><br><span class="line">  &quot;use strict&quot;;</span><br><span class="line">  foo():  &#x2F;&#x2F; 输出2</span><br><span class="line">)();</span><br></pre></td></tr></table></figure>
<p>由于我们可能会使用众多第三方库，所以代码中可能会混合使用strict模式和非strict模式，因此一定要注意这类的兼容性问题。</p>
</blockquote>
</li>
</ul>
<h4 id="2-2-2-隐式绑定"><a href="#2-2-2-隐式绑定" class="headerlink" title="2.2.2 隐式绑定"></a>2.2.2 隐式绑定</h4><ul>
<li>第二条规则，就是通过函数调用位置，函数是否属于某个对象的属性。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span>,</span><br><span class="line">    foo : foo</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj.foo();  <span class="comment">// 输出 2</span></span><br></pre></td></tr></table></figure></li>
<li>你看<code>foo()</code>方法的声明方式，它是被当做引用属性添加到了<code>obj</code>对象中，这种情况下，<code>obj</code>对象拥有/包含了<code>foo()</code>方法。</li>
<li>当函数有包含自己的对象时，隐式绑定规则会把<code>this</code>绑定到这个对象。</li>
<li>因此，调用<code>foo()</code>时，<code>this</code>被绑定到了<code>obj</code>对象，在函数中<code>this.a</code>和<code>obj.a</code>的引用是一样的。</li>
<li>值得注意的是，如果是多层嵌套对象下的函数，就只在最后一层中起作用。举例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a : <span class="number">2</span>,</span><br><span class="line">    obj2 : &#123;</span><br><span class="line">        a : <span class="number">42</span>,</span><br><span class="line">        foo : foo</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj1.obj2.foo();    <span class="comment">//输出 42</span></span><br></pre></td></tr></table></figure></li>
<li>值得注意的是，如果将<code>obj1.obj2.foo</code>函数的引用赋值给另一个变量，然后以默认绑定的方式调用函数，不管是自定义的函数，还是JS的内置函数，则还是会应用默认绑定规则：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">&#x27;oops,global&#x27;</span>;</span><br><span class="line"><span class="keyword">var</span> bar = obj1.obj2.foo;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">runFoo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    obj1.obj2.foo();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 都是输出 &#x27;oops,global&#x27;</span></span><br><span class="line">bar();  </span><br><span class="line">runfoo();   </span><br><span class="line"><span class="built_in">setTimeout</span>(obj1.obj2.foo,<span class="number">100</span>);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h4 id="2-2-3-显示绑定"><a href="#2-2-3-显示绑定" class="headerlink" title="2.2.3 显示绑定"></a>2.2.3 显示绑定</h4><ul>
<li>如果不想在对象内部包含函数引用，想在某个对象上强制调用函数，该怎么做呢?</li>
<li>JavaScript中的函数都有一些特性，可以用来解决这个问题。比如函数的<code>call()</code>和<code>applay()</code>方法</li>
<li>这两个方法，传入的第一个参数是一个对象，就是留给<code>this</code>准备的，调用时会将其绑定到<code>this</code>。因为可以直接指定<code>this</code>的绑定对象，因此我们称之为显示绑定。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;;</span><br><span class="line">foo.call(obj);  <span class="comment">// 输出 2</span></span><br></pre></td></tr></table></figure></li>
<li>但如果传入的参数是原始值（字符串、布尔或者数值类型）当做<code>this</code>的绑定对象的话，这个原始值会被转换成它的对象形式。也就是<code>new String()</code>、<code>new Boolean()</code>或者<code>new Number()</code>，这个过程通常叫做 <strong>装箱</strong> 。</li>
<li><strong>1. 硬绑定</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    foo.call(obj);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">bar();  <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">setTimeout</span>(bar,<span class="number">100</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//硬绑定不能再修改它的this</span></span><br><span class="line">bar.call(<span class="built_in">window</span>);   <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></li>
<li>函数<code>bar()</code>在它内部手动调用了<code>foo.call(obj)</code>，强制把<code>foo</code>的<code>this</code>绑定到了<code>obj</code>。无论之后如何调用函数<code>bar</code>，总会手动在<code>obj</code>上调用<code>foo</code>。这种显式的强制绑定，称之为硬绑定。</li>
<li>硬绑定的典型应用场景就是创建一个包裹函数，负责接收参数并返回值：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> foo.apply(obj,<span class="built_in">arguments</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>); <span class="comment">// 2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">// 5</span></span><br></pre></td></tr></table></figure></li>
<li>另一种方式就是创建一个可以重复使用的辅助函数：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    cosnole.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">fn,obj</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn.apply(obj,<span class="built_in">arguments</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = bind(foo,obj);</span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>);    <span class="comment">// 2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b);    <span class="comment">// 5</span></span><br></pre></td></tr></table></figure></li>
<li>由于硬绑定是一种非常常用的模式，所以ES5提供了内置方法<code>Function.prototype.bind</code>：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a,something);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.a + something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(obj);</span><br><span class="line"><span class="keyword">var</span> b = bar(<span class="number">3</span>); <span class="comment">// 2 3</span></span><br><span class="line"><span class="built_in">console</span>.log(b);    <span class="comment">// 5</span></span><br></pre></td></tr></table></figure></li>
<li><code>bind()</code>会返回一个硬编码的新函数，它会把你指定的参数设置为<code>this</code> 的上下文，并调用原始函数。</li>
<li><strong>2. API调用的“上下文”</strong></li>
<li>许多函数都提供了一个可选的参数，其作用和<code>bind()</code>函数一样，确保你的回调函数使用指定的<code>this</code>。举例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">el</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(el,<span class="built_in">this</span>.id);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    id : <span class="string">&#x27;awesome&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>].forEach(foo,obj);</span><br></pre></td></tr></table></figure></li>
<li>通过<code>call()</code>和<code>apply()</code>实现显示绑定，可以少写代码。<h4 id="2-2-4-new绑定"><a href="#2-2-4-new绑定" class="headerlink" title="2.2.4 new绑定"></a>2.2.4 new绑定</h4></li>
<li>在讲解最后一条<code>this</code>的绑定规则之前，首先要澄清一个常见的关于JavaScript中函数和对象的误解。</li>
<li>在传统的面向类的语言中，“构造函数”是类中的一些特殊方法，使用new初始化类时会调用类的构造函数，<code>something = new MyClass()</code>。然而，JavaScript中的new的机制实际上和面向类的语言完全不同。</li>
<li>我们重新定义一些JavaScript中的“构造函数”：在JavaScript中，构造函数只是使用new操作符时被调用的函数，它们并不属于某一个对象，也不会实例化一个类。</li>
<li>所有函数都可以用new来调用，这种函数调用被称为构造函数调用。实际上，并不存在所谓的“构造函数”，只有对函数的“构造调用”。</li>
<li>使用new来调用函数，会自动执行下面的操作：<ol>
<li>创建一个全新的对象</li>
<li>这个新对象会被执行[[Prototype]]连接</li>
<li>这个新对象会绑定到函数调用的this</li>
<li>如果函数没有返回其他对象，那么new表达式的函数调用会自动返回这个新对象。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.a = a;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> foo(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(bar.a); <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></li>
</ol>
</li>
<li>使用new来调用<code>foo()</code>时，我们会构造一个新对象，把它绑定到<code>foo()</code>调用中的this上，我们称之为new绑定。<h2 id="2-3-优先级"><a href="#2-3-优先级" class="headerlink" title="2.3 优先级"></a>2.3 优先级</h2></li>
<li>上文通过大篇幅讲了函数调用中，this绑定的四条规则：默认绑定、隐式绑定、显示绑定和new绑定。但如果调用应用了多条规则就必须给这些规则设定优先级了。</li>
<li>毫无疑问，默认绑定的优先级是最低的，暂不考虑它。</li>
<li>隐式绑定和显示绑定哪一个优先级更高？我们来测试一下：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a : <span class="number">2</span>,</span><br><span class="line">    foo : foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    a : <span class="number">3</span>,</span><br><span class="line">    foo : foo</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">obj1.foo(); <span class="comment">//2</span></span><br><span class="line">obj2.foo(); <span class="comment">//3</span></span><br><span class="line"></span><br><span class="line">obj1.foo.call(obj2);    <span class="comment">// 3</span></span><br><span class="line">obj2.foo.call(obj1);    <span class="comment">// 3</span></span><br></pre></td></tr></table></figure></li>
<li>可以看到，显式绑定优先级更高。</li>
<li>接下来，我们要测试，new绑定和隐式绑定的优先级谁高谁低：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.a = something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    foo : foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;&#125;</span><br><span class="line"></span><br><span class="line">obj1.foo(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">//2</span></span><br><span class="line"></span><br><span class="line">obj1.foo.call(obj2,<span class="number">3</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj2.a);    <span class="comment">//3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = <span class="keyword">new</span> obj1.foo(<span class="number">4</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">//2</span></span><br><span class="line"><span class="built_in">console</span>.log(bar.a);    <span class="comment">//2</span></span><br></pre></td></tr></table></figure></li>
<li>可以看到new绑定比隐式绑定的优先级更高，<code>obj1.a</code>的值一直没改变。</li>
<li>那new绑定和显示绑定，谁的优先级更高呢？（由于new和call/apply无法一起使用，所以通过硬绑定来测试）<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">something</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.a = something;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(obj1);</span><br><span class="line">bar(<span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">//2</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> baz = <span class="keyword">new</span> bar(<span class="number">3</span>);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">console</span>.log(baz.a);     <span class="comment">// 3</span></span><br></pre></td></tr></table></figure></li>
<li>观察输出的结果，<code>bar</code>被硬绑定到了<code>obj1</code>上，但<code>new baz(3)</code>并没有把<code>obj1.a</code>修改为3.</li>
<li>话说回来，之所以在new中使用硬绑定函数，主要目的是想预先设置一些参数，这样在使用new进行初始化时就可以传入其他参数了。举例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">p1,p2</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.val = p1 + p2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(<span class="literal">null</span>,<span class="string">&quot;p1&quot;</span>);</span><br><span class="line"><span class="keyword">var</span> baz = <span class="keyword">new</span> bar(<span class="string">&quot;p2&quot;</span>);</span><br><span class="line">baz.val;    <span class="comment">//p1p2</span></span><br></pre></td></tr></table></figure></li>
<li>根据优先级就能判断函数调用时应用的是哪条规则了，判断的步骤：<ol>
<li> 函数是否进行了new调用，如果是的话，this绑定的是新创建的对象；</li>
<li> 函数是否通过<code>call</code>、<code>apply</code>或者硬绑定调用，如果有的话，this绑定的是指定的对象；</li>
<li> 函数是否在某个对象中调用，如果是的话，this绑定的是该对象；</li>
<li> 如果都不是的话，使用默认绑定，绑定到全局对象。（严格模式下，绑定到undefined）</li>
</ol>
</li>
</ul>
<h2 id="2-4-绑定例外"><a href="#2-4-绑定例外" class="headerlink" title="2.4 绑定例外"></a>2.4 绑定例外</h2><h4 id="2-4-1-被忽略的this"><a href="#2-4-1-被忽略的this" class="headerlink" title="2.4.1 被忽略的this"></a>2.4.1 被忽略的this</h4><ul>
<li>把null或者undefined作为this传入call、apply或者bind，这些值在函数调用时会被忽略，应用默认的绑定规则：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">foo.call(<span class="literal">null</span>); <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></li>
<li>什么场景下会传入null呢？比如使用apply来遍历输出一个数组，或者通过<code>bind()</code>进行柯里化：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a,b</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;a:&#x27;</span>+a+<span class="string">&#x27;b:&#x27;</span>+b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo.apply(<span class="literal">null</span>,[<span class="number">2</span>,<span class="number">3</span>]); <span class="comment">// a:2,b:3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//先预先传入参数a</span></span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(<span class="literal">null</span>,<span class="number">2</span>);</span><br><span class="line"><span class="comment">//调用时再传入参数b</span></span><br><span class="line">bar(<span class="number">3</span>); <span class="comment">// a:2,b:3</span></span><br></pre></td></tr></table></figure></li>
<li>但这种方式可能会导致许多难以分析和追踪的bug，我们可以用更安全的方式。</li>
<li>更安全的做法就是不传入null，而是传入一个空的对象，把this绑定到这个对象，就好像创建一个非军事区的隔离对象一样，以确保不会对你的程序产生任何副作用。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a,b</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;a:&#x27;</span>+a+<span class="string">&#x27;b:&#x27;</span>+b);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> o = <span class="built_in">Object</span>.create(<span class="literal">null</span>);</span><br><span class="line">foo.apply(o,[<span class="number">2</span>,<span class="number">3</span>]); <span class="comment">// a:2,b:3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//先预先传入参数a</span></span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(o,<span class="number">2</span>);</span><br><span class="line"><span class="comment">//调用时再传入参数b</span></span><br><span class="line">bar(<span class="number">3</span>); <span class="comment">// a:2,b:3</span></span><br></pre></td></tr></table></figure></li>
<li>我们通过<code>Object.create(null)</code>来创建对象，它和直接以字面量<code>&#123;&#125;</code>创建对象很相似，但前者不会创建<code>Object.prototype</code>的委托，所以它比<code>&#123;&#125;</code>更空。</li>
</ul>
<h4 id="2-4-2-间接引用"><a href="#2-4-2-间接引用" class="headerlink" title="2.4.2 间接引用"></a>2.4.2 间接引用</h4><ul>
<li>另一个需要注意的是，可能会有意无意的创建一个函数的“间接引用”，而在这种情况下，调用这个函数会应用默认绑定规则。间接引用最容易在赋值时发生：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">    a : <span class="number">3</span>,</span><br><span class="line">    foo : foo</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> p = &#123; </span><br><span class="line">    a : <span class="number">4</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">o.foo(); <span class="comment">// 3</span></span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    p.foo = o.foo</span><br><span class="line">&#125;)();   <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<h4 id="2-4-3-软绑定"><a href="#2-4-3-软绑定" class="headerlink" title="2.4.3 软绑定"></a>2.4.3 软绑定</h4></li>
<li>硬绑定可以把this强制绑定到指定的对象，以防止函数调用应用默认绑定规则。问题在于，硬绑定会大大降低函数的灵活性，硬绑定之后，就无法使用隐式绑定或者显示绑定来修改this。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(!<span class="built_in">Function</span>.prototype.softbind)&#123;</span><br><span class="line">    <span class="built_in">Function</span>.prototype.softbind = <span class="function"><span class="keyword">function</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> fn = <span class="built_in">this</span>;</span><br><span class="line">        <span class="keyword">var</span> curried = [].slice.call(<span class="built_in">arguments</span>,<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">var</span> bound = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> fn.apply(</span><br><span class="line">                (!<span class="built_in">this</span> || <span class="built_in">this</span> === (<span class="built_in">window</span> || <span class="built_in">global</span>)) ? obj : <span class="built_in">this</span>,</span><br><span class="line">                curried.concat.apply(curried,<span class="built_in">arguments</span>)</span><br><span class="line">            );</span><br><span class="line">        &#125;;</span><br><span class="line">        bound.prototype = <span class="built_in">Object</span>.create(fn.prototype);</span><br><span class="line">        <span class="keyword">return</span> bound;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;name:&#x27;</span> + <span class="built_in">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">        name : <span class="string">&quot;obj&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    obj2 = &#123;</span><br><span class="line">        name : <span class="string">&quot;obj2&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    obj3 = &#123;</span><br><span class="line">        name : <span class="string">&quot;obj3&quot;</span></span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> fooOBJ = foo.softbind(obj);</span><br><span class="line"></span><br><span class="line">fooOBJ();   <span class="comment">// name : obj</span></span><br><span class="line"></span><br><span class="line">obj2.foo = foo.softbind(obj);</span><br><span class="line">obj2.foo(); <span class="comment">// name : obj2</span></span><br><span class="line"></span><br><span class="line">fooOBJ.call(obj3);  <span class="comment">// name : obj3</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(obj2.foo,<span class="number">10</span>);    <span class="comment">// name : obj</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="2-5-this词法"><a href="#2-5-this词法" class="headerlink" title="2.5 this词法"></a>2.5 this词法</h2></li>
<li>前面解说的四条规则几乎也包含所有函数，但ES6中介绍了一种无法使用这些规则的特殊函数类型：__箭头函数__。</li>
<li>箭头函数使用操作符<code>=&gt;</code>来定义，箭头函数不适用this的四种标准规则，而是根据外层作用域来决定this。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function">(<span class="params">a</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    a : <span class="number">3</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = foo.call(obj1);</span><br><span class="line">bar.call(obj2); <span class="comment">// 2 , 不是 3 !</span></span><br></pre></td></tr></table></figure></li>
<li>箭头函数最常用于回调函数中，例如事件处理器或者定时器：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">this</span>.a);</span><br><span class="line">    &#125;,<span class="number">100</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">2</span></span><br><span class="line">&#125;;</span><br><span class="line">foo.call(obj); <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="2-6-小结"><a href="#2-6-小结" class="headerlink" title="2.6 小结"></a>2.6 小结</h2><ul>
<li>如果要判断一个运用中函数的this绑定，需要找到函数的调用位置，然后按顺序应用四条规则来判断this的绑定对象：<ol>
<li>由new调用？绑定到新创建的对象；</li>
<li>由call或者apply/bind调用？绑定到指定的对象；</li>
<li>由对象调用？绑定到那个对象；</li>
<li>默认：严格模式下绑定到undefined，否则绑定到全局对象；</li>
</ol>
</li>
<li>有些调用无意中使用默认绑定规则。如果想“更安全” 地忽略this绑定，可以使用一个空的临时对象，比如<code>o = Object.create(null)</code>，以保护全局对象。</li>
<li>ES6中的箭头函数并不会使用四条标准的绑定规则，而是根据当前的词法作用域来决定this。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E02/" title="《你不知道的JavaScript(上)》S02E02">https://gitee.com/lianghuilin/murmur.git/reading_notes/《你不知道的JavaScript-上-》S02E02/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/murmur/tags/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/" rel="tag"># 你不知道的JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E01/" rel="prev" title="《你不知道的JavaScript(上)》S02E01">
                  <i class="fa fa-chevron-left"></i> 《你不知道的JavaScript(上)》S02E01
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E03/" rel="next" title="《你不知道的JavaScript(上)》S02E03">
                  《你不知道的JavaScript(上)》S02E03 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
